<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NTreeSelect,
  type TreeSelectOption,
  NButton,
  NPagination,
  NDataTable,
  type DataTableColumns,
  NFlex,
  NImage,
  NEllipsis
} from 'naive-ui'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import type { DjRecordClueTableRow } from '@/api/djRecord'
import { onMounted, ref, reactive, h } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'

const isDefineSubItems = (e: DjRecordClueTableRow) => e.subItems && e.subItems.length

const route = useRoute()

const columns: DataTableColumns<DjRecordClueTableRow> = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (e, index) => (isDefineSubItems(e) ? index + 1 : null)
  },
  {
    title: '征集品编码',
    key: 'subItemCode',
    align: 'center'
  },
  {
    title: '征集品名称',
    key: 'itemName',
    align: 'center'
  },
  {
    title: '类型',
    key: 'itemType',
    align: 'center'
  },
  {
    title: '数量',
    key: 'num',
    align: 'center',
    render: (e) => {
      if (isDefineSubItems(e)) return e.subItems.length
      return '1'
    }
  },
  {
    title: '年代',
    key: 'years',
    align: 'center'
  },
  {
    title: '备注',
    key: 'remark',
    align: 'center',
    render({ remark }) {
      return h(
        NEllipsis,
        { lineClamp: 2 },
        {
          default: () => remark,
          tooltip: () => {
            return h('div', { style: 'width: 200px' }, { default: () => remark })
          }
        }
      )
    }
  },
  {
    title: '图片',
    key: 'imageIds',
    render({ _imageFiles }) {
      if (!_imageFiles) return
      return h(
        NFlex,
        {},
        {
          default: () =>
            _imageFiles.map((e) =>
              h(NImage, {
                src: e.path,
                width: 50
              })
            )
        }
      )
    }
  }
]

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

const formData = reactive({} as any)
const tableData = ref<DjRecordClueTableRow[]>([])
const tableLoading = ref(false)
const queryTableData = async (reset = false) => {
  if (reset) paginationReactive.page = 1

  tableLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponsePagination<DjRecordClueTableRow>>({
      module: 'djRecord',
      api: 'itemList',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          djRecordId: route.query.id,
          batchId: batchId,
          ...formData
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.list.forEach((e) => (e.subItemCode = e.itemCode))
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount

    tableData.value.forEach((item) => {
      if (!item.imageIds) return
      sendRequest({
        module: 'upload',
        api: 'list',
        override: {
          params: {
            ids: item.imageIds
          }
        }
      }).then(([error, res]) => {
        if (error || res.code !== 0) return
        item._imageFiles = res.data
      })
    })
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

let batchId = ''
const queryWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'djRecord',
    api: 'workFlow',
    override: {
      params: {
        djRecordId: route.query.id
      }
    }
  })

  if (error) throw error
  if (res.code !== 0) throw new Error(res.msg)
  batchId = res.data.batchId
}

// 版本类型下拉框
const versionTypeOptions = ref<TreeSelectOption[]>([])
const versionTypeLoading = ref(false)
const queryVersionTypeOptions = async () => {
  versionTypeLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<TreeSelectOption[]>>({
      module: 'collector',
      api: 'versionListTreeAll',
      override: {
        params: {
          statusCode: 'A4901'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    handleVersionOptionsLeaf(res.data as unknown as VersionOption[])
    versionTypeOptions.value = res.data.length ? res.data : []
  } catch (error) {
    console.error(error)
  } finally {
    versionTypeLoading.value = false
  }
}
interface VersionOption {
  childList?: VersionOption[]
  classificationCode: string
  classificationName: string
  isLeaf: boolean
}
// 如果 childList是空数组，则此节点是leaf为true的节点，并且把childList置为undefined
const handleVersionOptionsLeaf = (options: VersionOption[]) => {
  options.forEach((e) => {
    if (e.childList?.length) {
      handleVersionOptionsLeaf(e.childList)
    } else {
      e.isLeaf = true
      e.childList = undefined
    }
  })
  return options
}

onMounted(async () => {
  await queryWorkFlow()
  queryTableData()
  queryVersionTypeOptions()
})
</script>

<template>
  <div class="dcl-title">点交</div>
  <div class="dcl-card">
    <NForm class="dcl-form">
      <NFormItem
        label="征集品名称："
        label-placement="left"
      >
        <NInput
          v-model:value="formData.itemName"
          placeholder="请输入征集品名称"
          clearable
        />
      </NFormItem>
      <NFormItem
        label="类型："
        label-placement="left"
      >
        <NTreeSelect
          v-model:value="formData.itemTypeCode"
          :options="versionTypeOptions"
          :loading="versionTypeLoading"
          labelField="classificationName"
          keyField="classificationCode"
          childrenField="childList"
          placeholder="请选择版本类型"
          clearable
          style="width: 230px"
        />
      </NFormItem>

      <NButton
        :disabled="tableLoading"
        :loading="tableLoading"
        color="#6CB187"
        ghost
        style="min-width: 78rem"
        @click="queryTableData(true)"
      >
        查询
      </NButton>
    </NForm>

    <NDataTable
      :loading="tableLoading"
      :data="tableData"
      :columns="columns"
      :row-key="(e) => e.subItemCode"
      children-key="subItems"
      max-height="400rem"
      style="margin-bottom: 30rem"
    />

    <NPagination
      show-size-picker
      show-quick-jumper
      :page-sizes="paginationReactive.pageSizes"
      :item-count="paginationReactive.itemCount"
      :page="paginationReactive.page"
      :page-size="paginationReactive.pageSize"
      @update:page="paginationReactive.onChange"
      @update:page-size="paginationReactive.onUpdatePageSize"
    >
      <template #suffix>页</template>
      <template #prefix>
        <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
      </template>
    </NPagination>
  </div>
</template>

<style lang="scss" scoped>
.dcl-title {
  font-size: 26rem;
  margin-bottom: 30rem;
  color: #048c5e;
  line-height: 1;
}

.dcl-card {
  padding: 20rem;
  background-color: #e1e1e1;
}

.dcl-form {
  display: flex;
  gap: 0 32rem;
}
</style>
